<!--------------------------------
 - @Author: Your Name
 - @LastEditor: Your Name
 - @LastEditTime: 2025-11-07
 - Copyright © 2025 Your Name
 --------------------------------->

<template>
  <CommonPage>
    <template #action>
      <NButton v-permission="'AddDesignFile'" type="primary" @click="handleUpload()">
        <i class="i-material-symbols:upload mr-4 text-18" />
        上传文件
      </NButton>
    </template>

    <MeCrud
      ref="$table"
      v-model:query-items="queryItems"
      :scroll-x="1400"
      :columns="columns"
      :get-data="api.read"
    >
      <MeQueryItem label="文件名" :label-width="70">
        <n-input
          v-model:value="queryItems.name"
          type="text"
          placeholder="请输入文件名"
          clearable
        />
      </MeQueryItem>

      <MeQueryItem label="文件类型" :label-width="70">
        <n-select
          v-model:value="queryItems.fileType"
          :options="fileTypeOptions"
          label-field="name"
          value-field="value"
          clearable
          placeholder="请选择文件类型"
        />
      </MeQueryItem>

      <MeQueryItem label="标签" :label-width="70">
        <n-select
          v-model:value="queryItems.tagId"
          :options="tags"
          label-field="name"
          value-field="id"
          clearable
          placeholder="请选择标签"
          filterable
        />
      </MeQueryItem>

      <MeQueryItem label="上传者" :label-width="70">
        <n-input
          v-model:value="queryItems.owner"
          type="text"
          placeholder="请输入上传者"
          clearable
        />
      </MeQueryItem>

      <MeQueryItem label="所属项目" :label-width="70">
        <n-select
          v-model:value="queryItems.projectId"
          :options="projects"
          label-field="name"
          value-field="id"
          clearable
          placeholder="请选择项目"
          filterable
        />
      </MeQueryItem>
    </MeCrud>

    <MeModal ref="uploadModalRef" width="600px" :title="uploadModalTitle">
      <n-form
        ref="uploadFormRef"
        label-placement="left"
        label-align="left"
        :label-width="100"
        :model="uploadForm"
      >
        <n-form-item label="文件" path="file">
          <NUpload
            v-model:file-list="uploadFileList"
            :max="1"
            :show-file-list="true"
            @change="handleFileChange"
          >
            <NButton>选择文件</NButton>
          </NUpload>
        </n-form-item>

        <n-form-item label="文件名" path="name">
          <n-input
            v-model:value="uploadForm.name"
            placeholder="请输入文件名"
          />
        </n-form-item>

        <n-form-item
          label="文件类型"
          path="fileType"
        >
          <n-select
            v-model:value="uploadForm.fileType"
            :options="fileTypeOptions"
            label-field="name"
            value-field="value"
            placeholder="请选择文件类型"
          />
        </n-form-item>

        <n-form-item label="标签" path="tags">
          <n-select
            v-model:value="uploadForm.tags"
            :options="tags"
            label-field="name"
            value-field="id"
            multiple
            filterable
            tag
            placeholder="请选择或创建标签"
          />
        </n-form-item>

        <n-form-item label="描述" path="description">
          <n-input
            v-model:value="uploadForm.description"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 5 }"
            placeholder="请输入文件描述"
          />
        </n-form-item>

        <n-form-item label="所属项目" path="projectId">
          <n-select
            v-model:value="uploadForm.projectId"
            :options="projects"
            label-field="name"
            value-field="id"
            clearable
            placeholder="请选择项目"
            filterable
          />
        </n-form-item>
      </n-form>

      <template #footer>
        <n-space justify="end">
          <NButton @click="uploadModalRef?.close()">
            取消
          </NButton>
          <NButton type="primary" :loading="uploadLoading" @click="handleUploadConfirm">
            创建
          </NButton>
        </n-space>
      </template>
    </MeModal>

    <MeModal ref="tagModalRef" width="500px" :title="tagModalTitle">
      <n-form
        ref="tagFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="tagForm"
      >
        <n-form-item
          label="标签名称"
          path="name"
          :rule="{
            required: true,
            message: '请输入标签名称',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="tagForm.name" placeholder="请输入标签名称" />
        </n-form-item>

        <n-form-item label="标签颜色" path="color">
          <NColorPicker v-model:value="tagForm.color" :show-alpha="false" />
        </n-form-item>
      </n-form>

      <template #footer>
        <n-space justify="end">
          <NButton @click="tagModalRef?.close()">
            取消
          </NButton>
          <NButton type="primary" :loading="tagLoading" @click="handleTagSave">
            保存
          </NButton>
        </n-space>
      </template>
    </MeModal>

    <!-- 版本管理模态框 -->
    <MeModal ref="versionModalRef" width="800px" :title="versionModalTitle">
      <div v-if="selectedFile">
        <n-descriptions label-placement="left" :column="2">
          <n-descriptions-item label="文件名">
            {{ selectedFile.name }}
          </n-descriptions-item>
          <n-descriptions-item label="当前版本">
            {{ selectedFile.version }}
          </n-descriptions-item>
          <n-descriptions-item label="文件类型">
            {{ fileTypeOptions.find(item => item.value === selectedFile.fileType)?.name || selectedFile.fileType }}
          </n-descriptions-item>
          <n-descriptions-item label="文件大小">
            {{ formatFileSize(selectedFile.fileSize) }}
          </n-descriptions-item>
        </n-descriptions>

        <n-divider>版本历史</n-divider>

        <n-data-table
          :columns="versionColumns"
          :data="fileVersions"
          :loading="versionsLoading"
        />

        <n-divider>创建新版本</n-divider>

        <n-form
          ref="newVersionFormRef"
          :model="newVersionForm"
          label-placement="left"
          label-align="left"
          :label-width="100"
        >
          <n-form-item label="版本号" path="versionNumber">
            <n-input
              v-model:value="newVersionForm.versionNumber"
              placeholder="请输入版本号，如：v1.1"
            />
          </n-form-item>

          <n-form-item label="版本描述" path="description">
            <n-input
              v-model:value="newVersionForm.description"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 5 }"
              placeholder="请输入版本描述"
            />
          </n-form-item>
        </n-form>
      </div>

      <template #footer>
        <n-space justify="end">
          <NButton @click="versionModalRef?.close()">
            关闭
          </NButton>
          <NButton type="primary" :loading="newVersionLoading" @click="handleCreateNewVersion">
            创建新版本
          </NButton>
        </n-space>
      </template>
    </MeModal>

    <!-- 编辑文件模态框 -->
    <MeModal ref="editModalRef" width="600px" :title="editModalTitle">
      <n-form
        ref="editFormRef"
        label-placement="left"
        label-align="left"
        :label-width="100"
        :model="editForm"
      >
        <n-form-item label="文件名" path="name">
          <n-input
            v-model:value="editForm.name"
            placeholder="请输入文件名"
          />
        </n-form-item>

        <n-form-item
          label="文件类型"
          path="fileType"
        >
          <n-select
            v-model:value="editForm.fileType"
            :options="fileTypeOptions"
            label-field="name"
            value-field="value"
            placeholder="请选择文件类型"
          />
        </n-form-item>

        <n-form-item label="标签" path="tags">
          <n-select
            v-model:value="editForm.tags"
            :options="tags"
            label-field="name"
            value-field="id"
            multiple
            filterable
            tag
            placeholder="请选择或创建标签"
          />
        </n-form-item>

        <n-form-item label="描述" path="description">
          <n-input
            v-model:value="editForm.description"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 5 }"
            placeholder="请输入文件描述"
          />
        </n-form-item>

        <n-form-item label="所属项目" path="projectId">
          <n-select
            v-model:value="editForm.projectId"
            :options="projects"
            label-field="name"
            value-field="id"
            clearable
            placeholder="请选择项目"
            filterable
          />
        </n-form-item>
      </n-form>

      <template #footer>
        <n-space justify="end">
          <NButton @click="editModalRef?.close()">
            取消
          </NButton>
          <NButton type="primary" :loading="editLoading" @click="handleEditSave">
            保存
          </NButton>
        </n-space>
      </template>
    </MeModal>
  </CommonPage>
</template>

<script setup>
import { NButton, NColorPicker, NTag, NUpload, NDataTable, NDescriptions, NDescriptionsItem, NDivider, NFormItem, NInputNumber, NSelect } from 'naive-ui'
import { MeCrud, MeModal, MeQueryItem } from '@/components'
import { formatDateTime, formatFileSize } from '@/utils'
import { designFileApi as api, designFileVersionApi } from '@/api/pms'
import JSZip from 'jszip'

defineOptions({ name: 'DesignFileMgt' })

const $table = ref(null)
/** QueryBar筛选参数（可选） */
const queryItems = ref({})

onMounted(() => {
  $table.value?.handleSearch()
})

// 文件类型选项
const fileTypeOptions = ref([])
api.getFileTypeOptions().then(({ data = [] }) => (fileTypeOptions.value = data))

// 标签列表
const tags = ref([])
api.getTags().then(({ data = [] }) => (tags.value = data))

// 项目列表
const projects = ref([])
import projectApi from '@/api/pms'
projectApi.read().then(({ data }) => {
  if (data && data.pageData) {
    projects.value = data.pageData
  }
})

// 版本管理相关
const versionModalRef = ref(null)
const versionModalTitle = ref('版本管理')
const selectedFile = ref(null)
const fileVersions = ref([])
const versionsLoading = ref(false)
const newVersionFormRef = ref(null)
const newVersionForm = ref({
  versionNumber: '',
  description: '',
})
const newVersionLoading = ref(false)

// 编辑文件相关
const editModalRef = ref(null)
const editModalTitle = ref('编辑文件')
const editFormRef = ref(null)
const editForm = ref({})
const editLoading = ref(false)

// 版本表格列定义
const versionColumns = [
  { title: '版本号', key: 'versionNumber', width: 150 },
  { title: '描述', key: 'description', width: 200, ellipsis: { tooltip: true } },
  { 
    title: '文件类型', 
    key: 'fileType', 
    width: 120,
    render: (row) => {
      const type = fileTypeOptions.value.find(item => item.value === row.fileType)
      return type ? h(NTag, { type: 'info' }, { default: () => type.name }) : row.fileType
    },
  },
  { 
    title: '文件大小', 
    key: 'fileSize', 
    width: 120,
    render: row => h('span', formatFileSize(row.fileSize)),
  },
  { 
    title: '操作类型', 
    key: 'operationType', 
    width: 120,
    render: (row) => {
      const typeMap = {
        CREATE: { text: '创建', type: 'success' },
        UPDATE: { text: '更新', type: 'info' },
        RESTORE: { text: '恢复', type: 'warning' },
      }
      const type = typeMap[row.operationType] || { text: row.operationType, type: 'default' }
      return h(NTag, { type: type.type }, { default: () => type.text })
    },
  },
  { 
    title: '版本状态', 
    key: 'versionStatus', 
    width: 120,
    render: (row) => {
      const statusMap = {
        ACTIVE: { text: '激活', type: 'success' },
        ARCHIVED: { text: '归档', type: 'default' },
      }
      const status = statusMap[row.versionStatus] || { text: row.versionStatus, type: 'default' }
      return h(NTag, { type: status.type }, { default: () => status.text })
    },
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180,
    render(row) {
      return h('span', formatDateTime(new Date(row.createTime)))
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'center',
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            class: 'ml-12px',
            onClick: () => handleRestoreVersion(row),
          },
          { default: () => '恢复' },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'info',
            secondary: true,
            class: 'ml-12px',
            onClick: () => handleViewVersionDetails(row),
          },
          { default: () => '详情' },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            secondary: true,
            class: 'ml-12px',
            onClick: () => handleDeleteVersion(row),
          },
          { default: () => '删除' },
        ),
      ]
    },
  },
]

// 上传模态框相关
const uploadModalRef = ref(null)
const uploadFormRef = ref(null)
const uploadForm = ref({
  name: '',
  fileType: null,
  tags: [],
  description: '',
  fileId: null,
  projectId: null,
})
const uploadFileList = ref([])
const uploadLoading = ref(false)
const uploadModalTitle = ref('上传设计文件')

// 标签模态框相关
const tagModalRef = ref(null)
const tagFormRef = ref(null)
const tagForm = ref({
  name: '',
  color: '#18a058',
})
const tagLoading = ref(false)
const tagModalTitle = ref('创建标签')

// 文件上传相关
function handleFileChange({ fileList }) {
  console.log('文件列表变化，新的文件列表:', fileList)
  uploadFileList.value = fileList
  if (fileList.length > 0) {
    const fileItem = fileList[0]
    console.log('第一个文件项:', fileItem)
    console.log('文件项的属性:', Object.keys(fileItem))
    
    // 检查fileItem是否有file属性
    if (fileItem.file) {
      const file = fileItem.file
      console.log('实际的File对象:', file)
      console.log('File对象的属性:', {
        name: file.name,
        size: file.size,
        type: file.type,
        lastModified: file.lastModified
      })
      
      // 自动填充文件名
      if (!uploadForm.value.name) {
        uploadForm.value.name = file.name
      }
      
      // 自动识别文件类型
      if (!uploadForm.value.fileType) {
        if (file.name.endsWith('.rp')) {
          uploadForm.value.fileType = 'AXURE_RP'
        }
        else if (file.name.endsWith('.zip')) {
          uploadForm.value.fileType = 'HTML_ZIP'
        }
        else if (file.name.endsWith('.fig')) {
          uploadForm.value.fileType = 'FIGMA'
        }
        else if (file.name.endsWith('.sketch')) {
          uploadForm.value.fileType = 'SKETCH'
        }
        else if (file.name.endsWith('.xd')) {
          uploadForm.value.fileType = 'ADOBE_XD'
        }
      }
      
      // 如果是HTML_ZIP类型的文件，才上传文件并获取ID
      if (uploadForm.value.fileType === 'HTML_ZIP') {
        uploadFileAndGetId(file)
      } else {
        // 对于其他类型的文件，也可以直接上传但不需要特殊验证
        uploadFileAndGetId(file)
      }
    } else {
      console.log('文件项中没有file属性')
    }
  } else {
    // 清除之前上传的文件ID
    uploadForm.value.fileId = null
  }
}

// 上传文件并获取ID
async function uploadFileAndGetId(file) {
  try {
    console.log('开始上传文件并获取ID...')
    
    // 如果是ZIP文件，检查是否包含index.html
    if (file.name.toLowerCase().endsWith('.zip')) {
      console.log('检测到ZIP文件，检查是否包含index.html...')
      
      try {
        const zip = new JSZip()
        const zipContent = await zip.loadAsync(file)
        
        // 检查是否包含index.html
        let hasIndexHtml = false
        for (const filename in zipContent.files) {
          // 检查文件名是否为index.html，忽略路径
          if (filename.toLowerCase().endsWith('index.html')) {
            hasIndexHtml = true
            break
          }
        }
        
        if (!hasIndexHtml) {
          throw new Error('ZIP文件必须包含index.html文件')
        }
        
        console.log('ZIP文件检查通过，包含index.html')
      } catch (zipError) {
        if (zipError.message === 'ZIP文件必须包含index.html文件') {
          $message.error(zipError.message)
          return // 返回，不继续上传
        }
        console.error('ZIP文件解析失败:', zipError)
        $message.error('无法解析ZIP文件: ' + zipError.message)
        return // 返回，不继续上传
      }
    }
    
    const fileFormData = new FormData()
    fileFormData.append('file', file)
    
    console.log('准备上传文件数据到后端...')
    console.log('FormData内容:', fileFormData.get('file'))
    console.log('FormData是否包含文件:', fileFormData.has('file'))

    // 调用仅上传文件的API
    console.log('调用uploadFileOnly API...')
    const fileUploadResult = await api.uploadFileOnly(fileFormData)
    console.log('文件上传API响应:', fileUploadResult)
    
    if (!fileUploadResult || !fileUploadResult.data || !fileUploadResult.data.id) {
      throw new Error('文件上传失败，未获取到文件ID')
    }
    
    const fileId = fileUploadResult.data.id
    console.log('文件上传成功，获取到文件ID:', fileId)
    
    // 将文件ID保存到表单中
    uploadForm.value.fileId = fileId
    $message.success('文件上传成功')
  }
  catch (error) {
    console.error('文件上传失败:', error)
    // 不显示错误消息，因为可能是验证失败导致的
    // $message.error('文件上传失败: ' + (error.message || '未知错误'))
  }
}

// 打开上传模态框
function handleUpload() {
  // 重置表单
  uploadForm.value = {
    name: '',
    fileType: null,
    tags: [],
    description: '',
    fileId: null,
    projectId: null,
  }
  uploadFileList.value = []
  uploadModalTitle.value = '上传设计文件'
  uploadModalRef.value?.open()
}

// 确认上传
async function handleUploadConfirm() {
  try {
    console.log('开始确认上传流程...')
    console.log('当前表单数据:', uploadForm.value)
    console.log('当前文件列表:', uploadFileList.value)
    console.log('文件列表长度:', uploadFileList.value?.length)
    console.log('当前文件ID:', uploadForm.value.fileId)
    console.log('当前文件类型:', uploadForm.value.fileType)
    
    // 检查是否已上传文件并获取了ID
    if (!uploadForm.value.fileId) {
      console.log('文件尚未上传或未获取到文件ID')
      $message.warning('请先选择文件并等待上传完成')
      return
    }
    
    // 检查文件类型是否已选择
    if (!uploadForm.value.fileType) {
      console.log('文件类型未选择')
      $message.warning('请选择文件类型')
      return
    }
    
    console.log('文件验证通过，开始表单验证...')
    
    // 检查表单验证的状态
    await new Promise((resolve, reject) => {
      uploadFormRef.value?.validate((errors) => {
        if (errors) {
          console.log('表单验证失败:', errors)
          // 打印每个验证错误的详细信息
          errors.forEach((error, index) => {
            console.log(`验证错误 ${index + 1}:`, error)
            console.log(`字段路径:`, error?.path)
            console.log(`错误信息:`, error?.message)
          })
          reject(new Error('表单验证失败'))
        } else {
          console.log('表单验证通过')
          resolve()
        }
      })
    })
    
    uploadLoading.value = true

    // 使用已获取的文件ID更新设计文件记录（绑定业务信息）
    const designFileData = {
      id: uploadForm.value.fileId,
      name: uploadForm.value.name,
      description: uploadForm.value.description,
      fileType: uploadForm.value.fileType,
      tags: uploadForm.value.tags || [],
      projectId: uploadForm.value.projectId,
    }
    
    console.log('准备更新设计文件记录，数据:', designFileData)

    const updateResult = await api.update(designFileData)
    console.log('设计文件更新API响应:', updateResult)

    uploadLoading.value = false
    $message.success('文件信息更新成功')
    uploadModalRef.value?.close()
    $table.value?.handleSearch()
  }
  catch (error) {
    uploadLoading.value = false
    console.error('上传失败详情:', error)
    console.error('错误堆栈:', error?.stack)
    const errorMessage = error.message || error.msg || error?.response?.data?.message || '上传失败'
    $message.error(errorMessage)
    console.error('上传失败:', error)
  }
}

// 打开标签模态框
function handleOpenTagModal() {
  tagForm.value = {
    name: '',
    color: '#18a058',
  }
  tagModalTitle.value = '创建标签'
  tagModalRef.value?.open()
}

// 保存标签
async function handleTagSave() {
  try {
    // 使用回调方式验证表单
    await new Promise((resolve, reject) => {
      tagFormRef.value?.validate((errors) => {
        if (errors) {
          console.log('标签表单验证失败:', errors)
          reject(new Error('标签表单验证失败'))
        } else {
          console.log('标签表单验证通过')
          resolve()
        }
      })
    })

    tagLoading.value = true

    const formData = {
      name: tagForm.value.name,
      color: tagForm.value.color,
      createdBy: 1, // 模拟当前用户ID
    }

    // 调用创建标签API
    const result = await api.createTag(formData)

    tagLoading.value = false
    $message.success('标签创建成功')
    tagModalRef.value?.close()

    // 更新标签列表
    tags.value.push(result.data)
  }
  catch (error) {
    tagLoading.value = false
    $message.error(error.message || '标签创建失败')
    console.error('标签创建失败:', error)
  }
}

const columns = [
  { title: '文件名', key: 'name', width: 200, ellipsis: { tooltip: true } },
  {
    title: '文件类型',
    key: 'fileType',
    width: 150,
    render: (row) => {
      const type = fileTypeOptions.value.find(item => item.value === row.fileType)
      return type ? h(NTag, { type: 'info' }, { default: () => type.name }) : row.fileType
    },
  },
  {
    title: '文件大小',
    key: 'fileSize',
    width: 120,
    render: row => h('span', formatFileSize(row.fileSize)),
  },
  {
    title: '标签',
    key: 'tags',
    width: 200,
    render: (row) => {
      if (row.tags && row.tags.length > 0) {
        return row.tags.map((tagId, index) => {
          const tag = tags.value.find(t => t.id === tagId)
          if (tag) {
            return h(
              NTag,
              {
                type: 'success',
                color: { color: tag.color, textColor: '#fff' },
                style: index > 0 ? 'margin-left: 8px;' : '',
              },
              { default: () => tag.name },
            )
          }
          return null
        }).filter(tag => tag !== null)
      }
      return '无标签'
    },
  },
  {
    title: '安全状态',
    key: 'securityStatus',
    width: 120,
    render: (row) => {
      const statusMap = {
        UNSCANNED: { text: '未扫描', type: 'warning' },
        SAFE: { text: '安全', type: 'success' },
        UNSAFE: { text: '不安全', type: 'error' },
      }
      const status = statusMap[row.securityStatus] || { text: '未知', type: 'default' }
      return h(NTag, { type: status.type }, { default: () => status.text })
    },
  },
  {
    title: '上传者',
    key: 'owner',
    width: 120,
    render: (row) => {
      // 模拟用户信息
      return `用户${row.ownerId}`
    },
  },
  {
    title: '所属项目',
    key: 'projectId',
    width: 150,
    render: (row) => {
      if (row.projectId) {
        const project = projects.value.find(p => p.id === row.projectId);
        return h('span', project ? project.name : `项目${row.projectId}`);
      }
      return h('span', '未绑定项目')
    },
  },
  {
    title: '创建时间',
    key: 'createdAt',
    width: 180,
    render(row) {
      return h('span', formatDateTime(new Date(row.createdAt)))
    },
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    render: (row) => {
      const statusMap = {
        NORMAL: { text: '正常', type: 'success' },
        DELETED: { text: '已删除', type: 'error' },
      }
      const status = statusMap[row.status] || { text: '未知', type: 'default' }
      return h(NTag, { type: status.type }, { default: () => status.text })
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 350,
    align: 'right',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            class: 'ml-12px',
            onClick: () => handleScan(row),
          },
          {
            default: () => '安全扫描',
            icon: () => h('i', { class: 'i-carbon:security text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            class: 'ml-12px',
            onClick: () => handlePreview(row),
          },
          {
            default: () => '预览',
            icon: () => h('i', { class: 'i-carbon:view text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'info',
            secondary: true,
            class: 'ml-12px',
            onClick: () => handleShare(row),
          },
          {
            default: () => '分享',
            icon: () => h('i', { class: 'i-carbon:share text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            class: 'ml-12px',
            onClick: () => handleEdit(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-material-symbols:edit-outline text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'info',
            class: 'ml-12px',
            disabled: !row.projectId,
            onClick: () => handleViewProject(row),
          },
          {
            default: () => '查看项目',
            icon: () => h('i', { class: 'i-material-symbols:visibility text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'info',
            class: 'ml-12px',
            onClick: () => handleOpenVersionModal(row),
          },
          {
            default: () => '版本',
            icon: () => h('i', { class: 'i-material-symbols:history text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row.id),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },
]

// 安全扫描
async function handleScan(row) {
  try {
    const result = await api.scanFileSecurity(row.id)
    $message.success(`安全扫描完成: ${result.data.securityStatus === 'SAFE' ? '文件安全' : '发现安全风险'}`)
    $table.value?.handleSearch()
    console.log('扫描结果:', result.data)
  }
  catch (error) {
    $message.error(`扫描失败: ${error.message}`)
    console.error('扫描失败:', error)
  }
}

// 预览文件
function handlePreview(row) {
  console.log('预览文件:', row)

  // 根据文件类型处理预览
  if (row.fileType === 'HTML_ZIP') {
    // HTML压缩包类型的预览 - 获取永久分享预览URL（基于文件ID，当前版本）
    api.getSharePreviewUrl(row.id, 'permanent').then(result => {
      if (result && result.data) {
        const previewUrl = result.data
        window.open(previewUrl, '_blank', 'width=1200,height=800,scrollbars=yes,resizable=yes')
        $message.success('正在打开HTML预览...')
      } else {
        $message.error('获取预览URL失败')
      }
    }).catch(error => {
      console.error('获取预览URL失败:', error)
      $message.error('获取预览URL失败: ' + error.message)
    })
  } else {
    // 其他文件类型的预览
    $message.info(`预览文件: ${row.name} (类型: ${row.fileType})`)

    // 如果是图片文件，可以尝试在新窗口打开
    if (row.fileType === 'IMAGE') {
      // 这里可以调用后端API获取图片URL，然后在新窗口打开
      // 暂时显示提示
      $message.warning('图片预览功能开发中，请下载后查看')
    } else {
      // 其他类型文件提供下载
      $message.warning('该文件类型暂不支持在线预览，请下载后查看')
    }
  }
}

// 分享文件
function handleShare(row) {
  console.log('分享文件:', row)

  // 根据文件类型处理分享
  if (row.fileType === 'HTML_ZIP') {
    // 简化实现 - 直接生成永久链接（基于文件ID，当前版本）
    api.getSharePreviewUrl(row.id, 'permanent').then(result => {
      if (result && result.data) {
        const shareUrl = result.data
        // 复制到剪贴板
        navigator.clipboard.writeText(shareUrl).then(() => {
          $message.success('分享链接已复制到剪贴板')
        }).catch(err => {
          console.error('复制失败:', err)
          // 如果复制失败，显示URL供手动复制
          $dialog.info({
            title: '分享链接',
            content: () => h('div', [
              h('p', '请手动复制以下链接进行分享：'),
              h('p', { style: { color: '#999', fontSize: '12px', marginBottom: '8px' }}, 
                '有效期: 永久'),
              h('input', {
                value: shareUrl,
                readonly: true,
                style: {
                  width: '100%',
                  padding: '8px',
                  marginTop: '8px',
                  borderRadius: '4px',
                  border: '1px solid #d9d9d9'
                },
                onClick: (e) => {
                  e.target.select()
                }
              })
            ]),
            positiveText: '确定'
          })
        })
      } else {
        $message.error('获取分享链接失败')
      }
    }).catch(error => {
      console.error('获取分享链接失败:', error)
      $message.error('获取分享链接失败: ' + error.message)
    })
  } else {
    // 其他文件类型的分享
    $message.info(`分享文件: ${row.name} (类型: ${row.fileType})`)
    $message.warning('该文件类型暂不支持分享功能')
  }
}

// 编辑文件
function handleEdit(row) {
  // 初始化编辑表单
  editForm.value = {
    id: row.id,
    name: row.name,
    description: row.description,
    fileType: row.fileType,
    tags: row.tags || [],
    projectId: row.projectId,
  }
  
  editModalTitle.value = `编辑文件: ${row.name}`
  editModalRef.value?.open()
}

// 保存编辑
async function handleEditSave() {
  try {
    await new Promise((resolve, reject) => {
      editFormRef.value?.validate((errors) => {
        if (errors) {
          console.log('编辑表单验证失败:', errors)
          reject(new Error('表单验证失败'))
        } else {
          console.log('编辑表单验证通过')
          resolve()
        }
      })
    })

    editLoading.value = true

    // 调用更新API
    const result = await api.update(editForm.value)

    editLoading.value = false
    $message.success('文件更新成功')
    editModalRef.value?.close()
    $table.value?.handleSearch()
  }
  catch (error) {
    editLoading.value = false
    $message.error(error.message || '文件更新失败')
    console.error('文件更新失败:', error)
  }
}

// 打开版本管理模态框
async function handleOpenVersionModal(row) {
  selectedFile.value = row
  versionModalTitle.value = `版本管理: ${row.name}`
  
  // 重置表单
  newVersionForm.value = {
    versionNumber: '',
    description: '',
  }
  
  // 加载版本历史
  await loadFileVersions(row.id)
  
  versionModalRef.value?.open()
}

// 加载文件版本历史
async function loadFileVersions(fileId) {
  try {
    versionsLoading.value = true
    const result = await designFileVersionApi.getVersionsByFileId(fileId)
    fileVersions.value = result.data || []
    versionsLoading.value = false
  }
  catch (error) {
    versionsLoading.value = false
    $message.error(error.message || '加载版本历史失败')
    console.error('加载版本历史失败:', error)
  }
}

// 创建新版本
async function handleCreateNewVersion() {
  try {
    await new Promise((resolve, reject) => {
      newVersionFormRef.value?.validate((errors) => {
        if (errors) {
          console.log('新版本表单验证失败:', errors)
          reject(new Error('表单验证失败'))
        } else {
          console.log('新版本表单验证通过')
          resolve()
        }
      })
    })

    newVersionLoading.value = true

    // 调用创建版本API
    const result = await designFileVersionApi.createVersion(selectedFile.value.id, newVersionForm.value)

    newVersionLoading.value = false
    $message.success('新版本创建成功')
    
    // 重新加载版本列表
    await loadFileVersions(selectedFile.value.id)
    
    // 重置表单
    newVersionForm.value = {
      versionNumber: '',
      description: '',
    }
  }
  catch (error) {
    newVersionLoading.value = false
    $message.error(error.message || '新版本创建失败')
    console.error('新版本创建失败:', error)
  }
}

// 恢复到指定版本
async function handleRestoreVersion(version) {
  try {
    const d = $dialog.warning({
      content: `确定要恢复到版本 ${version.versionNumber} 吗？这将替换当前文件内容。`,
      title: '确认恢复',
      positiveText: '确定',
      negativeText: '取消',
      async onPositiveClick() {
        try {
          d.loading = true
          const result = await designFileVersionApi.restoreToVersion(selectedFile.value.id, version.versionNumber)
          $message.success(`已恢复到版本 ${version.versionNumber}`)
          d.loading = false
          
          // 重新加载版本列表
          await loadFileVersions(selectedFile.value.id)
          
          // 刷新主表格
          $table.value?.handleSearch()
        }
        catch (error) {
          console.error(error)
          d.loading = false
          $message.error(error.message || '版本恢复失败')
        }
      },
    })
  }
  catch (error) {
    $message.error(error.message || '版本恢复失败')
    console.error('版本恢复失败:', error)
  }
}

// 查看项目详情
function handleViewProject(row) {
  if (!row.projectId) {
    $message.warning('该文件未绑定项目')
    return
  }

  // 查找项目信息
  const project = projects.value.find(p => p.id === row.projectId)
  if (!project) {
    $message.warning('项目信息不存在')
    return
  }

  // 显示项目详情对话框
  $dialog.info({
    title: '项目详情',
    content: () => [
      h('div', { style: { marginBottom: '8px' }}, [
        h('strong', '项目名称: '),
        h('span', project.name)
      ]),
      h('div', { style: { marginBottom: '8px' }}, [
        h('strong', '项目描述: '),
        h('span', project.description || '无')
      ]),
      h('div', { style: { marginBottom: '8px' }}, [
        h('strong', '项目状态: '),
        h('span', project.status || '未知')
      ]),
      h('div', { style: { marginBottom: '8px' }}, [
        h('strong', '可见性: '),
        h('span', project.visibility || '未知')
      ]),
      h('div', { style: { marginBottom: '8px' }}, [
        h('strong', '创建时间: '),
        h('span', project.createTime ? formatDateTime(new Date(project.createTime)) : '未知')
      ])
    ],
    positiveText: '确定'
  })
}

// 查看版本详情
function handleViewVersionDetails(version) {
  // 显示版本详情对话框
  $dialog.info({
    title: `版本详情: ${version.versionNumber}`,
    content: () => [
      h('div', { style: { marginBottom: '8px' }}, [
        h('strong', '版本号: '),
        h('span', version.versionNumber)
      ]),
      h('div', { style: { marginBottom: '8px' }}, [
        h('strong', '版本描述: '),
        h('span', version.description || '无')
      ]),
      h('div', { style: { marginBottom: '8px' }}, [
        h('strong', '文件类型: '),
        h('span', fileTypeOptions.value.find(item => item.value === version.fileType)?.name || version.fileType)
      ]),
      h('div', { style: { marginBottom: '8px' }}, [
        h('strong', '文件大小: '),
        h('span', formatFileSize(version.fileSize))
      ]),
      h('div', { style: { marginBottom: '8px' }}, [
        h('strong', '文件MD5: '),
        h('span', version.fileMd5 || '无')
      ]),
      h('div', { style: { marginBottom: '8px' }}, [
        h('strong', '操作类型: '),
        h('span', version.operationType)
      ]),
      h('div', { style: { marginBottom: '8px' }}, [
        h('strong', '版本状态: '),
        h('span', version.versionStatus)
      ]),
      h('div', { style: { marginBottom: '8px' }}, [
        h('strong', '创建时间: '),
        h('span', version.createTime ? formatDateTime(new Date(version.createTime)) : '未知')
      ]),
      h('div', { style: { marginBottom: '8px' }}, [
        h('strong', '更新时间: '),
        h('span', version.updateTime ? formatDateTime(new Date(version.updateTime)) : '未知')
      ])
    ],
    positiveText: '确定'
  })
}

// 删除版本
async function handleDeleteVersion(version) {
  const d = $dialog.warning({
    content: `确定删除版本 ${version.versionNumber}？此操作不可恢复。`,
    title: '确认删除版本',
    positiveText: '确定',
    negativeText: '取消',
    async onPositiveClick() {
      try {
        d.loading = true
        await designFileVersionApi.deleteVersion(version.id)
        $message.success(`版本 ${version.versionNumber} 删除成功`)
        d.loading = false
        
        // 重新加载版本列表
        await loadFileVersions(selectedFile.value.id)
      }
      catch (error) {
        console.error(error)
        d.loading = false
        $message.error(error.message || '版本删除失败')
      }
    },
  })
}

// 删除文件
function handleDelete(id) {
  const d = $dialog.warning({
    content: '确定删除该文件？',
    title: '提示',
    positiveText: '确定',
    negativeText: '取消',
    async onPositiveClick() {
      try {
        d.loading = true
        await api.delete(id)
        $message.success('删除成功')
        d.loading = false
        $table.value?.handleSearch()
      }
      catch (error) {
        console.error(error)
        d.loading = false
        $message.error(error.message || '删除失败')
      }
    },
  })
}
</script>
